//
//  LMMeController.m
//  舍品
//
//  Created by 楼 眉 on 16/3/21.
//  Copyright © 2016年 楼 眉. All rights reserved.
//
static         CGFloat         const            meSpace                     =                10;
static         CGFloat         const            nicknameFont            =                20;
static    NSString    *const    KUserInformationChange   =   @"userInformationChange";


#import "LMMeController.h"
#import "LMMeCollectionCell.h"
#import "LMProfilePostViewController.h"
#import "LMImageController.h"
#import <YYWebImage.h>
#import <MJRefresh.h>
#import "LMPostFrame.h"
#import "LMProfileStaticController.h"
#import "LMWarningLabel.h"
#import "LMProfileSetController.h"
#import "LMActionAccountController.h"

@interface LMMeController ()<UICollectionViewDataSource,UICollectionViewDelegate>
/**
 *  头像
 */
@property (nonatomic,weak)  UIImageView *iconImageView;
/**
 *  顶部背景
 */
@property (nonatomic,strong)  UIImageView *topBgView;
/**
 *  昵称
 */
@property (nonatomic,weak)  UILabel *nicknameLabel;
/**
 *  签名
 */
@property (nonatomic,weak)  UILabel *signLabel;
/**
 *  帖子列表
 */
@property (nonatomic,strong)  UICollectionView *collView;
/**
 *  帖子内容数组
 */
@property (nonatomic,strong)   NSArray *contents;
/**
 *  用户
 */
@property (nonatomic,strong)  LMUser *user;

@end

@implementation LMMeController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setUserInformation) name:KUserInformationChange object:nil];
    
    [self setupUi];
    [self setUserInformation];
    [self requestData];
    [self.collView registerClass:[LMMeCollectionCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
}
#pragma mark - 从user中设置用户信息
- (void)setUserInformation
{
    LMUser *user = [LMUser currentUser];
    NSData *imageData = [user.iconImage getData];
    if (imageData) {
        self.iconImageView.image = [UIImage imageWithData:imageData];
    }else
    {
        self.iconImageView.image = [UIImage imageNamed:@"touxiang.png"];
    }
    if (user.nickname)
    {
    self.nicknameLabel.text = user.nickname;
    }else
    {
        self.nicknameLabel.text = user.username;
    }
    self.signLabel.text = user.signString;
    if (!user) {
        self.contents = nil;
        [self.collView reloadData];
    }
    [self requestData];
}

/**
 *  请求数据并赋值
 */
- (void)requestData
{
    LMUser *user = [LMUser currentUser];
    if (user) {
        AVRelation *relation = [user relationForKey:@"posts"];
        AVQuery *query = [relation query];
        [query orderByDescending:@"createdAt"];
        __weak typeof(self) weakSelf = self;
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (objects) {
                weakSelf.contents = objects;
                [weakSelf.collView reloadData];
            }
            else
            {
                NSLog(@"请求数据失败");
            }
            [weakSelf.collView.mj_header endRefreshing];
        }];
    }
    else
    {
        [self.collView.mj_header endRefreshing];
    }
}

/**
 *  初始化界面
 */
- (void)setupUi
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    //大背景
    UIScrollView *bgView = [[UIScrollView alloc]init];
    bgView.bounces = NO;
    bgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
//    bgView.alwaysBounceVertical = YES;
    bgView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:bgView];
    
    //顶部背景
    UIImageView *topBgView = [[UIImageView alloc]init];
    topBgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 2.2);
//    topBgView.backgroundColor = RGBCOLOR(250, 169, 224);
    topBgView.image = [UIImage imageNamed:@"meBg.jpg"];
    topBgView.contentMode = UIViewContentModeScaleAspectFill;
    topBgView.clipsToBounds = YES;
    topBgView.userInteractionEnabled = YES;
    [bgView addSubview:topBgView];
    
    //设置按钮
    UIButton *setBtn = [[UIButton alloc]init];
    setBtn.frame = CGRectMake(SCREEN_WIDTH - 50*kUnit - 20*kUnit, 20 *kUnit, 50*kUnit, 50*kUnit);
    [setBtn setTitle:@"设置" forState:UIControlStateNormal];
    [setBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [setBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];
    [topBgView addSubview:setBtn];
    [setBtn addTarget:self action:@selector(setBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    //头像
    UIImageView *iconImageView = [[UIImageView alloc]init];
    iconImageView.clipsToBounds = YES;
    iconImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.iconImageView = iconImageView;
    iconImageView.frame = CGRectMake(topBgView.width / 6, topBgView.height / 4.5, SCREEN_WIDTH / 3.5, SCREEN_WIDTH / 3.5);
    iconImageView.backgroundColor = [UIColor lightGrayColor];
    [CALayer LM_RoundedImageWIthImageViewCALayer:iconImageView.layer Width:iconImageView.width];
    [topBgView addSubview:iconImageView];
    iconImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *iconTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(iconTaped)];
    [iconImageView addGestureRecognizer:iconTap];
    
    //昵称
    UILabel *nicknameLabel = [[UILabel alloc]init];
    self.nicknameLabel = nicknameLabel;
    nicknameLabel.textColor = [UIColor whiteColor];
    nicknameLabel.numberOfLines = 0;
    nicknameLabel.font = [UIFont systemFontOfSize:nicknameFont];
    nicknameLabel.frame = CGRectMake(CGRectGetMaxX(iconImageView.frame) + meSpace *kUnit, iconImageView.y, 200 *kUnit, iconImageView.height);
    [topBgView addSubview:nicknameLabel];
    
    //签名
    UILabel *signLabel = [[UILabel alloc]init];
    signLabel.textColor = [UIColor whiteColor];
    signLabel.textAlignment = NSTextAlignmentCenter;
    signLabel.frame = CGRectMake(0, CGRectGetMaxY(iconImageView.frame) + meSpace *2*kUnit, SCREEN_WIDTH, 33 *kUnit);
    self.signLabel = signLabel;
    [topBgView addSubview:signLabel];
    
    //修改资料
    UIButton *changBtn = [[UIButton alloc]init];
    changBtn.frame = CGRectMake(0, CGRectGetMaxY(signLabel.frame) + meSpace *2 *kUnit, SCREEN_WIDTH / 3.5, 33*kUnit);
    changBtn.backgroundColor = RGBCOLOR(29, 89, 30);
    [changBtn.layer setMasksToBounds:YES];
    [changBtn.layer setCornerRadius:10.0]; //设置矩形四个圆角半径
    [changBtn.layer setBorderWidth:1.0]; //边框宽度
    changBtn.x = (SCREEN_WIDTH - changBtn.width) / 2;
    [changBtn setTitle:@"修改资料" forState:UIControlStateNormal];
    [changBtn addTarget:self action:@selector(changBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [topBgView addSubview:changBtn];
    
    //底部展示帖子用的collectionView
    UICollectionViewFlowLayout *ft = [[UICollectionViewFlowLayout alloc]init];
    ft.itemSize = CGSizeMake((SCREEN_WIDTH - 40*kUnit) / 2, (SCREEN_WIDTH - 40*kUnit) / 1.8);
    ft.sectionInset = UIEdgeInsetsMake(10 *kUnit, 10*kUnit, 10*kUnit, 10*kUnit);
    CGRect collRect =CGRectMake(0, CGRectGetMaxY(topBgView.frame), SCREEN_WIDTH,SCREEN_HEIGHT - topBgView.height - self.tabBarController.tabBar.height);
    UICollectionView *collView = [[UICollectionView alloc]initWithFrame:collRect collectionViewLayout:ft];
    self.collView = collView;
    
    __weak typeof (self)weakSelf = self;
    collView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
        if (manager.isReachable == NO) {
            [LMWarningLabel LM_createWarningLabelWithTitle:nil];
            [collView.mj_header endRefreshing];
            return;
        }
        else
        {
            [weakSelf requestData];
        }
    }];
    collView.backgroundColor = [UIColor grayColor];
    collView.delegate = self;
    collView.dataSource = self;
    [bgView addSubview:collView];
}
#pragma mark - 设置按钮被点击
- (void)setBtnClick
{
    if ([LMUser currentUser]) {
        UIStoryboard *setSb = [UIStoryboard storyboardWithName:@"profileSet" bundle:[NSBundle mainBundle]];
        LMProfileSetController *setVc = [setSb instantiateViewControllerWithIdentifier:@"profileSetSB"];
        [self.navigationController pushViewController:setVc animated:YES];
    }
    else
    {
        [self toLogin];
    }
}
#pragma mark - 头像图片被点击
- (void)iconTaped
{
    LMImageController *imageVc = [[LMImageController alloc]init];
    UIImage *iconImage = self.iconImageView.image;
    if (iconImage == nil) {
        [LMWarningLabel LM_createWarningLabelWithTitle:@"您还未设置头像"];
    }else
    {
    imageVc.image = iconImage;
    [self presentViewController:imageVc animated:YES completion:nil];
    }
}
#pragma mark - 修改按钮被点击
- (void)changBtnClick
{
    if ([AFNetworkReachabilityManager sharedManager].isReachable == YES) {
        if ([LMUser currentUser]) {
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"ProfileStatic" bundle:[NSBundle mainBundle]];
            LMProfileStaticController *staticVc = [storyboard instantiateViewControllerWithIdentifier:@"profileSB"];
            staticVc.view.backgroundColor = [UIColor lightGrayColor];
            [self.navigationController pushViewController:staticVc animated:YES];
        }
        else
        {
            [self toLogin];
        }
    }else
    {
        [LMWarningLabel LM_createWarningLabelWithTitle:@"没有网络"];
    }
}
#pragma mark - 跳转注册登录页面
- (void)toLogin
{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"您还未登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *logInAction = [UIAlertAction actionWithTitle:@"去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        LMActionAccountController *loginVc = [[LMActionAccountController alloc]init];
        [self.navigationController pushViewController:loginVc animated:YES];
    }];
    [alertVc addAction:logInAction];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"先看看" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVc addAction:cancel];
    [self presentViewController:alertVc animated:YES completion:nil];
}
#pragma mark - 隐藏导航栏
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    self.navigationController.navigationBarHidden = YES;
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.navigationController.navigationBarHidden = NO;
}
#pragma mark -  didReceiveMemoryWarning
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
#pragma mark - collectionView actions
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.contents.count;
}

//每个UICollectionView展示的内容
-(LMMeCollectionCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"UICollectionViewCell";
    LMMeCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    LMPost *post = self.contents[indexPath.row];
    cell.post = post;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    LMPost *post = self.contents[indexPath.row];
    LMProfilePostViewController *moreVc = [[LMProfilePostViewController alloc]init];
    [self.navigationController pushViewController:moreVc animated:YES];
    moreVc.post = post;
}
#pragma mark - 销毁通知
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KUserInformationChange object:nil];
    NSLog(@"dealloc--meVc");
}
@end
